﻿/*
	Copyright (c) 2009, SpLib.net
  	All rights reserved.
  	
  	Author:6spring
  	About:BaseObj 提供Event的注册/分发
*/

package org.dm.objSys
{
	import SpLib.Com.EveNode;
	import SpLib.Com.SpLibEvent;
	import org.dm.utils.Utils;
	import org.dm.utils.Iterator;
	import org.dm.utils.Map
	
	import flash.events.EventDispatcher;
	import flash.system.ApplicationDomain;
	import flash.utils.getDefinitionByName;
	
	public class BaseObj extends EventDispatcher
	{	
		private var m_EveMap:Map = new Map();
		public var m_bDeled:Boolean = false;
		
		public function BaseObj()
		{
			super();
		}
		
		public static function CreateObj(classname:String):BaseObj
		{
			
			var domain : ApplicationDomain = ApplicationDomain.currentDomain;
			if(domain.hasDefinition(classname))
			{
				var regclass:Class = getDefinitionByName(classname) as Class; 
				if(regclass!=null)
				{
					return _CreateObjAsClass(regclass);
				}
			}
			
			return null;
		}
		
		private static function _CreateObjAsClass(classname:Class):BaseObj
		{
			var retobj:BaseObj = new classname() as BaseObj;
			return retobj;
		}
		
		protected function RegEvent(evename:String,func:Function):void
		{
			var eve:SpLib.Com.EveNode = new SpLib.Com.EveNode(evename,func)
			var eveid:uint = Utils.Str2Key(evename);
			var iter:Iterator = m_EveMap.find(eveid);
			if(iter!=null)
			{
				var oldeve:SpLib.Com.EveNode = iter.data as SpLib.Com.EveNode;
				removeEventListener(evename,oldeve.m_Func);
			}
			
			m_EveMap.setvalue(eveid,eve);
			
			var evefullname:String = "SpLibObjEvent_" + evename;
			addEventListener(evefullname,func);
		}
		
		public function EventAsID(eveid:uint,agv:Array):void
		{
			if(!m_bDeled)
			{
				var evenode:Iterator = m_EveMap.find(eveid);
				if(evenode!=null) 
				{
					var eve:SpLib.Com.EveNode = evenode.data as SpLib.Com.EveNode;
					var evefullname:String = "SpLibObjEvent_" + eve.m_sEvename;
					dispatchEvent(new SpLibEvent(evefullname,eve.m_sEvename,agv));
				}
			}
		}
		
		public function Event(eve:String,agv:Array):void
		{
			var eveid:uint = Utils.Str2Key(eve);
			EventAsID(eveid,agv);
		}
		
		public function DelObj():void
		{
			if(m_bDeled==false)
			{
				m_bDeled = true;
				dispatchEvent(new SpLibEvent(SpLibEvent.OBJDELTHIS,"OnDelObj"));
				m_EveMap.clear();
			}
		}
	}
}